
// 只进行翻译前后映射
// 多语言文件监控
import { exec } from "child_process";
import chokidar from "chokidar";
import path from "path";
import fs from "fs";

export default function lanMonitor() {

  return {
    name: 'lan-monitor',
    configureServer: () => {
      console.log("子进程开启成功");
      const lanDir = path.resolve(__dirname, "../script/lan");
      const hiddenDir = path.resolve(__dirname, "../src/lan");
      const hasMap = fs.existsSync(hiddenDir);

      const watcher = chokidar.watch(`${lanDir}/*.json`, {
        depth: 1, ignoreInitial: true
      });

      watcher.on('add', (src) => {
        if (!hasMap) {
          fs.mkdirSync(hiddenDir, { recursive: true });
          exec(`attrib +h "${hiddenDir}"`);
        }
        fs.copyFileSync(src, path.resolve(hiddenDir, path.basename(src)));
        console.log(`File ${src} has been added`);
      });

      watcher.on('unlink', (src) => {
        hiddenDir && fs.unlinkSync(path.resolve(hiddenDir, path.basename(src)))
        console.log(`File ${src} has been removed`);
      });

      watcher.on('error', (error) => {
        console.error('Error happened', error);
      });
    }
  }
}